const axios = require('axios');
const { inputJobInfoByAPI } = require('./operationTCF.js');
const { getExtractedData } = require('./getAuchanData.js');
const { sendMonitoringData } = require('./user-data.js');
const path = require('path');
const fs = require('fs');

// 读取manifest.json
let manifest = {};
try {
    const manifestPath = path.join(__dirname, 'manifest.json');
    manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
} catch (error) {
    console.warn('无法读取manifest.json:', error.message);
    manifest = { version: '1.0.0' };
}

// 获取 token 
const getToken = async (baseAuthUrl, username, password) => {
  try {
    const authUrl = baseAuthUrl;
    const response = await axios.post(authUrl, {
      username,
      password
    });
    console.log('获取token成功');
    return response.data.token;
  } catch (error) {
    console.error('获取 token 失败:', error.message);
    throw error;
  }
};

// 配置信息
const CONFIG = {
  baseUrl: "http://cnap452:10674/data/config",
  baseAuthUrl: "http://cnap452:10674/auth/login",
  createJobUrl: "http://cnap452:10674/data/jobs"
};

/**
 * 主函数：处理TCF输入流程
 * @param {string} orderNumber - 订单号
 * @param {string} username - 用户名（可选，默认使用配置中的用户名）
 * @param {string} password - 密码（可选，默认使用配置中的密码）
 * @param {Object} userSettings - 用户设置
 * @returns {Promise<Object>} - 处理结果
 */
async function processTCFInput(orderNumbers, apiUsername, apiPassword, extractionUsername, extractionPassword, userSettings = {}) {
  console.log(`开始处理订单: ${orderNumbers.join(', ')}`);
  
  console.log(`使用API账号: ${apiUsername}`);
  console.log(`使用提取账号: ${extractionUsername}`);
  
  try {
    // 步骤1: 获取认证令牌
    console.log('正在获取认证令牌...');
    const token = await getToken(CONFIG.baseAuthUrl, apiUsername, apiPassword);
    
    // 步骤2: 获取订单数据（传入登录凭据）
    console.log('正在从系统获取订单数据...');
    const data = await getExtractedData(orderNumbers, extractionUsername, extractionPassword);
    console.log(`成功获取到 ${data.length} 条数据记录`);
    
    // 步骤3: 通过API创建Job
    console.log('正在创建Job...');
    await inputJobInfoByAPI(CONFIG.createJobUrl, token, data);
    console.log('Job创建成功');
    
    // 步骤4: 发送监控数据
    try {
      const monitoringData = {
        user_name: userSettings.email?.split('@')[0] || 'unknown',
        user_location: userSettings.site || 'unknown',
        rpa_id: "141",
        rpa_name: "TCF_Input",
        rpa_version: manifest.version,
        occurrence: new Date().toLocaleString('en-US', {
          weekday: 'short',
          day: '2-digit',
          month: 'short',
          year: 'numeric',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }),
        info: "TCF Input - Auchan产品信息提取和TCF Job创建",
        extra: `${orderNumbers.join(', ')}`
      };
      
      const monitoringResult = await sendMonitoringData([monitoringData]);
      console.log(`监控数据发送${monitoringResult.success ? '成功' : '失败'}: ${monitoringResult.message}`);
    } catch (monitoringError) {
      console.error(`发送监控数据时出错: ${monitoringError.message}`);
    }
    
    // 返回成功结果和数据
    return {
      success: true,
      message: '处理成功',
      data: data,
      processedAt: new Date().toISOString()
    };
    
  } catch (error) {
    console.error('处理过程中出错:', error);
    // 返回错误信息
    return {
      success: false,
      message: `处理失败: ${error.message}`,
      error: error.message,
      stack: error.stack
    };
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  // 从命令行参数获取订单号、用户名和密码
  const args = process.argv.slice(2);
  // 假设所有参数都是订单号，直到遇到非订单号格式的参数
  const orderNumbers = args.filter(arg => arg.startsWith('P')); // 简单的过滤逻辑，可以根据实际单号格式调整
  const apiUsername = args.find(arg => arg.startsWith('apiUser='));
  const apiPassword = args.find(arg => arg.startsWith('apiPass='));
  const extractionUsername = args.find(arg => arg.startsWith('extUser='));
  const extractionPassword = args.find(arg => arg.startsWith('extPass='));

  if (orderNumbers.length === 0) {
      console.log('无单号'); // 如果没有提供订单号，使用默认值
  }

  processTCFInput(
    orderNumbers,
    apiUsername ? apiUsername.split('=')[1] : undefined,
    apiPassword ? apiPassword.split('=')[1] : undefined,
    extractionUsername ? extractionUsername.split('=')[1] : undefined,
    extractionPassword ? extractionPassword.split('=')[1] : undefined,
    {} // 命令行模式下使用空的用户设置
  )
    .then(result => {
      console.log('处理完成:', result);
      process.exit(0);
    })
    .catch(error => {
      console.error('处理失败:', error.message);
      process.exit(1);
    });
} else {
  // 作为模块导出
  module.exports = processTCFInput;
}